/*
 * Adiciona noticia
 * */
package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.Autor;
import beans.Noticia;
import beans.Tag;
import dbclass.AutorDAO;
import dbclass.AutorJDBC;
import dbclass.NoticiaDAO;
import dbclass.NoticiaJDBC;
import dbclass.TagDAO;
import dbclass.TagJDBC;

/**
 * Servlet implementation class NoticiasAdd
 */
public class NoticiasAdd extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NoticiasAdd() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(true);
		//Verifica login
		if(session.getValue("autor_login") == null) {
			response.sendRedirect("Home?msg_erro=Acesso Negado");  return;
		} 
		
		Autor autor = (Autor) session.getAttribute("autor_login");
		
		
		String url = null;
		NoticiaDAO noticiaDAO = new NoticiaJDBC();

		//Adicionar Noticia
		String titulo = request.getParameter("titulo");
		String corpo = request.getParameter("corpo");
		String data = request.getParameter("data");
		long id_categoria = (long)Integer.parseInt(request.getParameter("id_categoria"));
		long id_autor = autor.getId();
		
		Noticia noticia = new Noticia(0, titulo, corpo, data, id_autor, id_categoria);
		noticia.setData(noticia.data_yyyymmdd());
		 
		try { 
				 
			Noticia insertedNoticia = noticiaDAO.insert(noticia); 

		    
			//Adicionar Tags
			String tags =  request.getParameter("tags");
			if(tags != null) {
					
				String[] array_tags = tags.split(",");
		
				if(array_tags.length > 0) {
					TagDAO tagdao = new TagJDBC();
					
					for(int i = 0; i < array_tags.length; i++){
						Tag tag = new Tag(array_tags[i], insertedNoticia.getId());
						tagdao.insert(tag);	 
					}
				}
			}
			
			url="Noticias?msg_sucesso=Noticia adicionada com sucesso";   
 
			response.sendRedirect(url); 
		} catch (ClassNotFoundException e) {  
			// TODO Auto-generated catch block 
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
